<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="../modules/js/common.js"></script>
</head>
<body>
<div align="center">
    <h1>购买页面</h1>
    <table class="table-bordered" width="200"  >
        <thead>
        <tr>
            <td >商品编号</td>
            <td >商品名称</td>
            <td >商品类型</td>
            <td >商品价格</td>
            <td >数   量</td>
            <td >总   价</td>
        </tr>
        </thead>
        <tbody id="tbody">

        </tbody>
    </table>
    <button onclick="buy()">确认购买</button>
    <button onclick="goBack()">返回</button>
</div>

<script>
    $(function (){
        $.ajax({
            url:"http://localhost:8080/item/"+$.cookie("buyId"),
            crossDomain:true,
            xhrFields: {withCredentials:true},
            success(result){
                $("#tbody").append(`<tr>
                        <td id="id">${result.data.id}</td>
                        <td id="name">${result.data.name}</td>
                        <td id="type">${result.data.type}</td>
                        <td id="price">${(result.data.price)*0.01}</td>
                        <td><select id="number" onchange="getTotalPrice()">
                               <option value="1">1</option>
                               <option value="2">2</option>
                               <option value="3">3</option>
                               <option value="4">4</option>
                               <option value="5">5</option>
                            </select></td>
                         <td id="totalPrice">${(result.data.price)*0.01}</td>
                         </tr>`)
            }
        })

    })


    function getTotalPrice(){
        $("#totalPrice").empty();
        let price=document.getElementById("price").innerHTML;
        let num=$("#number option:selected").val();
        $("#totalPrice").append(price*num);
    }

    function buy(){
        let id=document.getElementById("id").innerHTML;
        let num=$("#number option:selected").val();
        $.ajax({
            method:"put",
            url:"http://localhost:8080/item/"+id+"/"+num,
            crossDomain: true,xhrFields: {withCredentials: true},
            success(result) {
                alert(result.message);
                window.location.href="http://localhost:8080/view/item.html";

            }
        })
        doOrder(id,num);

    }

    function doOrder(id,num){
        let username=$.cookie("username");
        $.ajax({
            method: "post",
            url:`http://localhost:8080/order/${username}/${id}/${num}`,
            crossDomain: true,xhrFields: {withCredentials: true},
            success(result){
                console.log("订单生成成功");
            }
        })

    }

    function goBack(){
        window.location.href="http://localhost:8080/view/item.html";
    }
</script>
</body>
</html>